from django.db import models
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from django_model_utils.fields import TemplateString, TemplateStringField
from django_model_utils.models import StatMixin, PageMixin


class Page(StatMixin, PageMixin, models.Model):
    title = models.CharField(max_length=150, verbose_name=_('Titel'))
    url = models.CharField(verbose_name=_('URL'), max_length=150, db_index=True, unique=True)
    base_template = models.CharField(verbose_name=_('Basis Template'), max_length=200, blank=True, null=True)
    content = TemplateStringField(verbose_name=_('Inhalt'), context_callback=lambda p: {'page': p})
    
    @property
    def template(self):
        base_template = 'page/base.html'
        if self.base_template:
            base_template = self.base_template
        content = self.content.content
        if not '{% block' in content:
            content = u'{%% block content %%}\n%s\n{%% endblock %%}' % content
        return TemplateString(
            u'{%% extends "%s" %%}\n%s\n' (base_template, content),
            self.content.taglibs,
            self.content.context_callback,
            self.content.parent_object,
        )
    
    def __unicode__(self):
        return u"%s -- %s" % (self.url, self.title)
    
    class Meta:
        verbose_name = _(u'Statische Seite')
        verbose_name_plural = _(u'Statische Seiten')
        ordering = ('url',)

